const API_BASE = "http://127.0.0.1:5000";

// ===== 房源列表 =====
async function loadHouses(page=1, per_page=5){
  try{
    const res = await fetch(`${API_BASE}/get/houselist?page=${page}&per_page=${per_page}`);
    const json = await res.json();
    if(json.code!==1) throw new Error(json.msg);
    renderList(json.data.houses);
    renderPager(json.data.page, json.data.per_page, json.data.total);
    renderRecommend(json.data.houses); // 个性化推荐
  }catch(e){
    document.getElementById('house-list').innerHTML = `<p>加载失败：${e.message}</p>`;
  }
}

function renderList(houses){
  const listEl = document.getElementById('house-list');
  listEl.innerHTML = houses.map(h=>`
    <article class="house">
      <h2>${h.title}</h2>
      <p>${h.address}</p>
      <p>${h.price} 元 · ${h.rooms} · ${h.area}㎡</p>
      <div class="house-actions">
        <button class="btn" onclick="addToCompare(${h.id},'${h.title}','${h.price}','${h.rooms}','${h.address}')">加入对比</button>
        <a class="btn" href="detail.html?id=${h.id}">查看详情</a>
      </div>
    </article>
  `).join('');
}

function renderPager(page, per_page, total){
  const pagerEl = document.getElementById('pager');
  const pages = Math.ceil(total/per_page);
  let html = "";
  for(let i=1;i<=pages && i<=5;i++){
    html += `<button onclick="loadHouses(${i},${per_page})" ${i===page?'style="font-weight:bold"':''}>${i}</button> `;
  }
  pagerEl.innerHTML = html;
}

// ===== 详情页 =====
async function loadDetail(){
  const id = new URLSearchParams(location.search).get("id");
  const res = await fetch(`${API_BASE}/get/houselist?page=1&per_page=100`);
  const data = await res.json();
  const item = data.data.houses.find(h=>String(h.id)===String(id));
  const area = document.getElementById('detail-area');
  if(!item){ area.innerHTML="<p>未找到房源</p>"; return; }
  area.innerHTML = `
    <h2>${item.title}</h2>
    <p>价格：${item.price}</p>
    <p>户型：${item.rooms}</p>
    <p>面积：${item.area}㎡</p>
    <p>地址：${item.address}</p>
    <p>房东：${item.landlord} (${item.phone_num})</p>
    <button class="btn" onclick="addToCompare(${item.id},'${item.title}','${item.price}','${item.rooms}','${item.address}')">加入对比</button>
  `;
  // 保存浏览历史
  let seen = JSON.parse(localStorage.getItem('seenList')||'[]');
  seen = seen.filter(i=>i.id!=item.id);
  seen.unshift({id:item.id,title:item.title,rooms:item.rooms,address:item.address});
  if(seen.length>20) seen.length=20;
  localStorage.setItem('seenList', JSON.stringify(seen));
}

// ===== 对比 =====
function addToCompare(id,title,price,rooms,address){
  let list = JSON.parse(localStorage.getItem('compareList')||'[]');
  if(list.find(x=>x.id==id)) return alert('已在对比列表');
  if(list.length>=3) return alert('最多对比3套');
  list.push({id,title,price,rooms,address});
  localStorage.setItem('compareList', JSON.stringify(list));
  alert('已加入对比');
}

function renderCompare(){
  const list = JSON.parse(localStorage.getItem('compareList')||'[]');
  const area = document.getElementById('compare-area');
  if(list.length===0){ area.innerHTML="<p>暂无对比房源</p>"; return; }
  area.innerHTML = list.map(it=>`
    <div class="compare-card">
      <h3>${it.title}</h3>
      <p>${it.price} 元</p>
      <p>${it.rooms}</p>
      <p>${it.address}</p>
      <a href="detail.html?id=${it.id}">详情</a>
    </div>
  `).join('');
}
function clearCompare(){ localStorage.removeItem('compareList'); renderCompare(); }

// ===== 地图找房 =====
async function loadMap(){
  const res = await fetch(`${API_BASE}/get/houselist?page=1&per_page=20`);
  const json = await res.json();
  const houses = json.data.houses;
  const map = L.map('map').setView([39.9,116.4], 12);
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{maxZoom:19}).addTo(map);
  houses.forEach(h=>{
    if(h.address){
      // 这里只能演示：没有 lat/lon，就用随机偏移模拟
      const lat = 39.9 + Math.random()*0.1;
      const lon = 116.3 + Math.random()*0.1;
      L.marker([lat,lon]).addTo(map).bindPopup(`<b>${h.title}</b><br>${h.price}元<br><a href="detail.html?id=${h.id}">详情</a>`);
    }
  });
}

// ===== 个性化推荐（基于浏览历史） =====
function renderRecommend(allHouses){
  const seen = JSON.parse(localStorage.getItem('seenList')||'[]');
  if(seen.length===0) return;
  const target = seen[0]; // 最近浏览的房源
  const rec = allHouses.filter(h=>h.rooms===target.rooms && h.id!=target.id).slice(0,3);
  const recEl = document.getElementById('recommend-list');
  if(recEl){
    recEl.innerHTML = rec.map(h=>`
      <div class="house">
        <h3>${h.title}</h3>
        <p>${h.price} 元 · ${h.rooms}</p>
        <a href="detail.html?id=${h.id}">查看详情</a>
      </div>
    `).join('');
  }
}
